package com.mytest;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.jms.*;

@Configuration
public class AppConfig {

    @Bean
    public Session session() throws JMSException {

        //1. 创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        //2. 创建连接 并 开启
        Connection connection = connectionFactory.createConnection();
        connection.start();
        //3. 创建Session
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        return session;
    }

    @Bean
    public MessageProducer messageProducer() throws JMSException {

        Session session = session();
        //4. 创建消息目的地
        Destination destination = session.createQueue("weixin-Queue");
        //5. 创建生产者
        MessageProducer producer = session.createProducer(destination);
        return producer;
    }

    @Bean
    public MessageConsumer messageConsumer() throws JMSException {

        //1. 创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
        //2. 创建并启动连接
        Connection connection = connectionFactory.createConnection();
        connection.start();
        //3. 创建Session
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        //4. 创建目的地对象
        Destination destination = session.createQueue("weixin-Queue");
        //5. 创建消费者
        MessageConsumer consumer = session.createConsumer(destination);

        //6. 获取消息
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println(textMessage.getText());
                    //Thread.sleep(10000);
                    /*if ("Hello,MQ33".equals(textMessage.getText())){
                        throw new RuntimeException("eeeeee");
                    }*/
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        });

        return consumer;
    }
}
